﻿using System.Collections.Generic;
using Avalonia.Controls;
using AvaloniaEdit.Rendering;

namespace MarkdownRow.Edit;

class ElementGenerator : VisualLineElementGenerator, IComparer<KeyValuePair<int, Control>>
{
    private List<KeyValuePair<int, Control>> Controls => new();

    /// <summary>
    /// Gets the first interested offset using binary search
    /// </summary>
    /// <returns>The first interested offset.</returns>
    /// <param name="startOffset">Start offset.</param>
    public override int GetFirstInterestedOffset(int startOffset)
    {
        var pos = Controls.BinarySearch(new KeyValuePair<int, Control>(startOffset, null!), this);
        if (pos < 0)
            pos = ~pos;
        if (pos < Controls.Count)
            return Controls[pos].Key;
        return -1;
    }

    public override VisualLineElement? ConstructElement(int offset)
    {
        int pos = Controls.BinarySearch(new KeyValuePair<int, Control>(offset, null!), this);
        return pos >= 0 ? new InlineObjectElement(0, Controls[pos].Value) : null;
    }

    int IComparer<KeyValuePair<int, Control>>.Compare(KeyValuePair<int, Control> x, KeyValuePair<int, Control> y)
    {
        return x.Key.CompareTo(y.Key);
    }
}